package com.dimples.dd.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dimples.dd.common.model.Option;
import com.dimples.dd.common.pojo.PageResult;
import com.dimples.dd.common.util.cache.CacheUtils;
import com.dimples.dd.system.convert.SmsChannelConvert;
import com.dimples.dd.system.framework.sms.core.client.SmsClient;
import com.dimples.dd.system.framework.sms.core.client.SmsClientFactory;
import com.dimples.dd.system.framework.sms.core.property.SmsChannelProperties;
import com.dimples.dd.system.mapper.SystemSmsChannelMapper;
import com.dimples.dd.system.model.entity.SystemSmsChannelDO;
import com.dimples.dd.system.model.form.SmsChannelForm;
import com.dimples.dd.system.model.query.SmsChannelPageQuery;
import com.dimples.dd.system.model.vo.SmsChannelPageVO;
import com.dimples.dd.system.service.SystemSmsChannelService;
import com.dimples.dd.system.service.SystemSmsTemplateService;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;

import static com.dimples.dd.common.exception.BizExceptionUtil.exception;
import static com.dimples.dd.common.exception.ErrorCode.SMS_CHANNEL_HAS_CHILDREN;
import static com.dimples.dd.common.exception.ErrorCode.SMS_CHANNEL_NOT_EXISTS;

@Service
@RequiredArgsConstructor
public class SystemSmsChannelServiceImpl extends ServiceImpl<SystemSmsChannelMapper, SystemSmsChannelDO> implements SystemSmsChannelService {

    private final SmsClientFactory smsClientFactory;

    private final SmsChannelConvert smsChannelConvert;

    @Resource
    private SystemSmsTemplateService smsTemplateService;

    /**
     * {@link SmsClient} 缓存，通过它异步刷新 smsClientFactory
     */
    @Getter
    private final LoadingCache<Long, SmsClient> idClientCache = CacheUtils.buildAsyncReloadingCache(Duration.ofSeconds(10L),
            new CacheLoader<>() {
                @NotNull
                @Override
                public SmsClient load(@NotNull Long id) {
                    // 查询，然后尝试刷新
                    SystemSmsChannelDO channel = baseMapper.selectById(id);
                    if (channel != null) {
                        SmsChannelProperties properties = smsChannelConvert.entity2Properties(channel);
                        smsClientFactory.createOrUpdateSmsClient(properties);
                    }
                    return smsClientFactory.getSmsClient(id);
                }

            });

    /**
     * {@link SmsClient} 缓存，通过它异步刷新 smsClientFactory
     */
    @Getter
    private final LoadingCache<String, SmsClient> codeClientCache = CacheUtils.buildAsyncReloadingCache(Duration.ofSeconds(60L),
            new CacheLoader<>() {
                @NotNull
                @Override
                public SmsClient load(@NotNull String code) {
                    // 查询，然后尝试刷新
                    SystemSmsChannelDO channel = baseMapper.selectOne(SystemSmsChannelDO::getCode, code);
                    if (channel != null) {
                        SmsChannelProperties properties = smsChannelConvert.entity2Properties(channel);
                        smsClientFactory.createOrUpdateSmsClient(properties);
                    }
                    return smsClientFactory.getSmsClient(code);
                }

            });

    @Override
    public Long createSmsChannel(SmsChannelForm createSmsChannelForm) {
        SystemSmsChannelDO channel = this.smsChannelConvert.form2Entity(createSmsChannelForm);
        this.save(channel);
        return channel.getId();
    }

    @Override
    public void updateSmsChannel(SmsChannelForm updateSmsChannelForm) {
        // 校验存在
        SystemSmsChannelDO channel = validateSmsChannelExists(updateSmsChannelForm.getId());
        // 更新
        SystemSmsChannelDO updateObj = this.smsChannelConvert.form2Entity(updateSmsChannelForm);
        this.baseMapper.updateById(updateObj);

        // 清空缓存
        clearCache(updateSmsChannelForm.getId(), channel.getCode());
    }

    /**
     * 清空指定渠道编号的缓存
     *
     * @param id   渠道编号
     * @param code 渠道编码
     */
    private void clearCache(Long id, String code) {
        idClientCache.invalidate(id);
        if (StrUtil.isNotEmpty(code)) {
            codeClientCache.invalidate(code);
        }
    }

    private SystemSmsChannelDO validateSmsChannelExists(Long id) {
        SystemSmsChannelDO channel = this.getById(id);
        if (channel == null) {
            throw exception(SMS_CHANNEL_NOT_EXISTS);
        }
        return channel;
    }

    @Override
    public void deleteSmsChannel(Long id) {
        // 校验存在
        SystemSmsChannelDO channel = validateSmsChannelExists(id);
        // 校验是否有在使用该账号的模版
        if (this.smsTemplateService.selectSmsTemplateCountByChannelId(id) > 0) {
            throw exception(SMS_CHANNEL_HAS_CHILDREN);
        }
        // 删除
        this.baseMapper.deleteById(id);

        // 清空缓存
        clearCache(id, channel.getCode());
    }

    @Override
    public SmsChannelForm selectSmsChannel(Long id) {
        return this.smsChannelConvert.entity2Form(this.baseMapper.selectById(id));
    }

    @Override
    public PageResult<SmsChannelPageVO> selectSmsChannelPage(SmsChannelPageQuery pageQuery) {
        PageResult<SystemSmsChannelDO> pageResult = this.baseMapper.selectPage(pageQuery);
        return this.smsChannelConvert.entity2Page(pageResult);
    }

    @Override
    public List<Option<Long>> listSmsChannelOptions() {
        return this.smsChannelConvert.entity2Options(this.baseMapper.listSmsChannelOptions());
    }

    @Override
    public SmsClient getSmsClient(Long channelId) {
        return idClientCache.getUnchecked(channelId);
    }

    @Override
    public SmsClient getSmsClient(String code) {
        return codeClientCache.getUnchecked(code);
    }
}
